Imports ClubStarterKit.Data
Imports ClubStarterKit.Web
Imports System.Linq
Imports System.Data.Linq
Imports System.Reflection
Imports System.Collections.Generic


Partial Class Statistics_EditStat
    Inherits System.Web.UI.Page

    Dim _matchId As Integer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        IsGameRecorder = User.IsInRole("GameRecorder")

        If Request("gameid") Is Nothing Then
            'Response.Write("<script>window.parent.hidePopWin()</script>")
            'Response.Write("<script>window.close()</script>")

            'for debug
            Response.Redirect("EditStat.aspx?gameid=3")

        Else
            _matchId = Integer.Parse(Request("gameid"))
            hlBcGame.NavigateUrl = hlBcGame.NavigateUrl + "?id=" + _matchId.ToString()

            If IsPostBack = False Then
                Try

                    Using dbcontext As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)
                        Dim match = (From m In dbcontext.Matches _
                                     Where m.MatchId = _matchId _
                                     Select m).Single()

                        hlBcGame.Text = match.Team.TeamName + " v " + match.OpponentTeam
                        lblGameTitle.Text = IIf(match.IsHome = True, hlBcGame.Text, match.OpponentTeam + " v " + match.Team.TeamName)

                        'TODO: BIND ANY BATTING AND BOWLING STATS HERE!
                        SetUpBatting(dbcontext)
                        SetUpBowling(dbcontext)

                    End Using

                Catch ex As Exception
                    ErrorLabel.Visible = True
                    ErrorLabel.Text = ex.Message
                End Try
            End If

        End If

    End Sub

    ''' <summary>
    ''' This bad boy rips through each row of the list view and updates or inserts
    ''' players stats...its a bit of a beast, might b nice to split some sub's out...
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub UpdateStats_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdateStats.Click

        Using dbcontext As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)

            WriteBattingStats(dbcontext)

            WriteBowlingStats(dbcontext)

            ' commit um
            dbcontext.SubmitChanges()

            'go back to game page
            Response.Redirect("~/CricketStats/Game.aspx?id=" + _matchId.ToString())
        End Using

    End Sub

    ''' <summary>
    ''' Write batting stats to the database context, they are NOT commited...
    ''' </summary>
    ''' <param name="dbContext"></param>
    ''' <remarks></remarks>
    Private Sub WriteBattingStats(ByVal dbContext As CricketBLL.CricketStatsDataContext)
        For Each item In lvBattingStats.Items
            Try
                Dim ddlPlayer As DropDownList = CType(item.FindControl("ddlPlayers"), DropDownList)

                ' If no player selected...move along...
                If ddlPlayer.SelectedIndex = 0 Then
                    Continue For
                End If

                Dim chkDNB As CheckBox = CType(item.FindControl("chkDNB"), CheckBox)
                Dim chkNO As CheckBox = CType(item.FindControl("chkNO"), CheckBox)
                Dim ddlHowOut As DropDownList = CType(item.FindControl("ddlHowOut"), DropDownList)
                Dim txtBowler As TextBox = CType(item.FindControl("txtBowler"), TextBox)
                Dim txtBallsFaced As TextBox = CType(item.FindControl("txtBallsFaced"), TextBox)
                Dim txtMins As TextBox = CType(item.FindControl("txtMins"), TextBox)
                Dim txtFours As TextBox = CType(item.FindControl("txtFours"), TextBox)
                Dim txtSixes As TextBox = CType(item.FindControl("txtSixes"), TextBox)
                Dim txtBatRuns As TextBox = CType(item.FindControl("txtBatRuns"), TextBox)
                Dim lblBatNum As Label = CType(item.FindControl("lblBatNum"), Label)
                Dim playerId As Integer = Integer.Parse(ddlPlayer.SelectedValue)

                Dim matchStat As New CricketBLL.PlayerStat()

                Dim stats = From s In dbContext.PlayerStats _
                            Where s.MatchId = _matchId AndAlso s.PlayerId = playerId _
                            Select s

                If stats.Count() = 1 Then
                    matchStat = stats.Single()
                ElseIf stats.Count() > 1 Then
                    Throw New Exception(String.Format("There should only be one record for a player in a match"))
                Else
                    matchStat = New CricketBLL.PlayerStat()
                End If

                matchStat.MatchId = _matchId
                matchStat.PlayerId = playerId
                matchStat.DNB = chkDNB.Checked
                matchStat.BatNumber = Integer.Parse(lblBatNum.Text)

                If chkDNB.Checked = False Then
                    'ignore is DNB
                    matchStat.NotOut = chkNO.Checked
                    If matchStat.NotOut = False Then
                        matchStat.HowOut = ddlHowOut.SelectedItem.Text
                        matchStat.BowlersName = txtBowler.Text
                    Else
                        matchStat.HowOut = String.Empty
                        matchStat.BowlersName = String.Empty
                    End If

                    If Not String.IsNullOrEmpty(txtMins.Text) Then
                        matchStat.MinutesInBat = Integer.Parse(txtMins.Text)
                    End If
                    If Not String.IsNullOrEmpty(txtFours.Text) Then
                        matchStat.FoursHit = Integer.Parse(txtFours.Text)
                    End If
                    If Not String.IsNullOrEmpty(txtSixes.Text) Then
                        matchStat.SixesHit = Integer.Parse(txtSixes.Text)
                    End If
                    If Not String.IsNullOrEmpty(txtBatRuns.Text) Then
                        matchStat.RunsScored = Integer.Parse(txtBatRuns.Text)
                    End If
                    If Not String.IsNullOrEmpty(txtBallsFaced.Text) Then
                        matchStat.BallsFaced = Integer.Parse(txtBallsFaced.Text)
                    End If
                Else
                    ' Did not bad so wipe out all values
                    matchStat.HowOut = String.Empty
                    matchStat.BowlersName = String.Empty
                    matchStat.MinutesInBat = Nothing
                    matchStat.FoursHit = Nothing
                    matchStat.SixesHit = Nothing
                    matchStat.RunsScored = Nothing
                    matchStat.BallsFaced = Nothing
                End If

                If stats.Count() < 1 Then
                    dbContext.PlayerStats.InsertOnSubmit(matchStat)
                End If

            Catch ex As Exception
                ErrorLabel.Visible = True
                ErrorLabel.Text = ex.Message
                Continue For
            End Try
        Next
    End Sub

    ''' <summary>
    ''' Write bowling stats the database context, they are NOT commited...
    ''' </summary>
    ''' <param name="dbContext"></param>
    ''' <remarks></remarks>
    Private Sub WriteBowlingStats(ByVal dbContext As CricketBLL.CricketStatsDataContext)
        For Each item In lvBowlingStats.Items
            Try
                Dim ddlPlayer As DropDownList = CType(item.FindControl("ddlPlayers"), DropDownList)

                ' Same deal: If no player selected...move along...
                If ddlPlayer.SelectedIndex = 0 Then
                    Continue For
                End If

                Dim txtOvers As TextBox = CType(item.FindControl("txtOvers"), TextBox)
                Dim txtMaidens As TextBox = CType(item.FindControl("txtMaidens"), TextBox)
                Dim txtRuns As TextBox = CType(item.FindControl("txtRuns"), TextBox)
                Dim txtWickets As TextBox = CType(item.FindControl("txtWickets"), TextBox)
                Dim txtCatches As TextBox = CType(item.FindControl("txtCatches"), TextBox)
                Dim lblBowlNum As Label = CType(item.FindControl("lblBowlNum"), Label)

                'if there is an existing record you will need to update rather than create new!
                Dim stats = From s In dbContext.PlayerStats _
                            Where s.PlayerId = Integer.Parse(ddlPlayer.SelectedValue) _
                            AndAlso s.MatchId = _matchId _
                            Select s

                Dim stat As CricketBLL.PlayerStat

                If stats.Count = 1 Then
                    'get Stat
                    stat = stats.Single()
                ElseIf stats.Count() > 1 Then
                    Throw New Exception(String.Format("There should only be one record for a player in a match"))
                Else
                    'New up object
                    stat = New CricketBLL.PlayerStat()
                End If

                stat.BowlerNumber = Integer.Parse(lblBowlNum.Text)

                If Not String.IsNullOrEmpty(txtOvers.Text) Then
                    stat.OversBowled = Integer.Parse(txtOvers.Text)
                End If
                If Not String.IsNullOrEmpty(txtMaidens.Text) Then
                    stat.Maidens = Integer.Parse(txtMaidens.Text)
                End If
                If Not String.IsNullOrEmpty(txtRuns.Text) Then
                    stat.Runs = Integer.Parse(txtRuns.Text)
                End If
                If Not String.IsNullOrEmpty(txtWickets.Text) Then
                    stat.Wickets = Integer.Parse(txtWickets.Text)
                End If
                If Not String.IsNullOrEmpty(txtCatches.Text) Then
                    stat.Catches = Integer.Parse(txtCatches.Text)
                End If

                If stats.Count < 1 Then
                    dbContext.PlayerStats.InsertOnSubmit(stat)
                End If

            Catch ex As Exception
                ErrorLabel.Visible = True
                ErrorLabel.Text = ex.Message
                Continue For
            End Try
        Next
    End Sub

    ''' <summary>
    ''' Build data for batting stats
    ''' </summary>
    ''' <param name="db"></param>
    ''' <remarks></remarks>
    Private Sub SetUpBatting(ByVal db As CricketBLL.CricketStatsDataContext)
        Try
            Dim batting = (From b In db.PlayerStats _
                          Where b.MatchId = _matchId AndAlso b.BatNumber.HasValue() _
                          Select b).ToList()

            For i = 1 To 11
                Dim bat = From b In batting _
                          Where b.BatNumber = i _
                          Select b
                If bat.Count() = 0 Then
                    Dim stat As New CricketBLL.PlayerStat()
                    stat.BatNumber = i
                    batting.Add(stat)
                End If
            Next

            lvBattingStats.DataSource = From b In batting _
                                        Order By b.BatNumber Ascending _
                                        Select b
            lvBattingStats.DataBind()


        Catch ex As Exception
            ErrorLabel.Visible = True
            ErrorLabel.Text = ex.Message
            ErrorLabel.ForeColor = Drawing.Color.Red
        End Try
    End Sub

    ''' <summary>
    ''' Build data for bowling stats
    ''' </summary>
    ''' <param name="db"></param>
    ''' <remarks></remarks>
    Private Sub SetUpBowling(ByVal db As CricketBLL.CricketStatsDataContext)
        Try
            Dim bowling = (From b In db.PlayerStats _
                          Where b.MatchId = _matchId AndAlso b.BowlerNumber.HasValue() _
                          Select b).ToList()

            For i = 1 To 11
                Dim bowl = From b In bowling _
                           Where b.BowlerNumber = i _
                           Select b
                If bowl.Count() = 0 Then
                    Dim stat As New CricketBLL.PlayerStat()
                    stat.BowlerNumber = i
                    bowling.Add(stat)
                End If
            Next

            lvBowlingStats.DataSource = From b In bowling _
                                        Order By b.BowlerNumber Ascending _
                                        Select b
            lvBowlingStats.DataBind()


        Catch ex As Exception

        End Try
    End Sub

    Protected Sub lvBattingStats_ItemDataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvBattingStats.ItemDataBound
        Try
            Dim itemArgs As ListViewItemEventArgs = CType(e, ListViewItemEventArgs)

            Dim ddlPlayers As DropDownList
            Dim hidFieldTemp As HiddenField

            ddlPlayers = CType(itemArgs.Item.FindControl("ddlPlayers"), DropDownList)

            If ddlPlayers Is Nothing = False Then
                InitPlayers()
                ddlPlayers.DataSource = _list
                ddlPlayers.DataBind()
                ddlPlayers.Items.Insert(0, "Select one...")
                hidFieldTemp = CType(itemArgs.Item.FindControl("hidPlayerId"), HiddenField)
                If String.IsNullOrEmpty(hidFieldTemp.Value) = False Then
                    ddlPlayers.SelectedValue = hidFieldTemp.Value
                End If
            End If
            Dim ddlHowOut As DropDownList = CType(itemArgs.Item.FindControl("ddlHowOut"), DropDownList)
            BindHowOutMethods(ddlHowOut)

            ' set how out value...
            hidFieldTemp = CType(itemArgs.Item.FindControl("hidHowOut"), HiddenField)
            If String.IsNullOrEmpty(hidFieldTemp.Value) = False Then
                ddlHowOut.SelectedValue = hidFieldTemp.Value
            End If

        Catch ex As Exception
            ErrorLabel.Visible = True
            ErrorLabel.Text = ex.Message
            ErrorLabel.ForeColor = Drawing.Color.Red
        End Try

    End Sub

    Protected Sub lvBowlingStats_ItemDataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvBowlingStats.ItemDataBound
        Try
            Dim itemArgs As ListViewItemEventArgs = CType(e, ListViewItemEventArgs)

            Dim ddlPlayers As DropDownList
            Dim hidFieldTemp As HiddenField

            ddlPlayers = CType(itemArgs.Item.FindControl("ddlPlayers"), DropDownList)

            If ddlPlayers Is Nothing = False Then
                InitPlayers()
                ddlPlayers.DataSource = _list
                ddlPlayers.DataBind()
                hidFieldTemp = CType(itemArgs.Item.FindControl("hidPlayerId"), HiddenField)
                If String.IsNullOrEmpty(hidFieldTemp.Value) = False Then
                    ddlPlayers.SelectedValue = hidFieldTemp.Value
                End If
            End If

        Catch ex As Exception

        End Try

    End Sub

    Dim _list As System.Collections.Generic.List(Of CricketBLL.Player)
    ''' <summary>
    ''' Initialise all players
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitPlayers()
        Try
            If (_list Is Nothing) Then

                Using dbcontext As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)

                    _list = (From p In dbcontext.Players _
                             Order By p.PlayerName _
                            Select p).ToList()

                End Using
            End If

        Catch ex As Exception
            ErrorLabel.Visible = True
            ErrorLabel.Text = ex.Message
        End Try
    End Sub

    Private m_isrec As Boolean = False
    Public Property IsGameRecorder() As Boolean
        Get
            Return m_isrec
        End Get
        Set(ByVal value As Boolean)
            m_isrec = value
        End Set
    End Property

    ''' <summary>
    ''' This little fella uses reflection to iterate the fields in the HowOut class
    ''' and binds them to the howout drop down
    ''' </summary>
    ''' <param name="ddl"></param>
    ''' <remarks>This is called on each row binding of the list view</remarks>
    Private Sub BindHowOutMethods(ByVal ddl As DropDownList)
        Try
            ddl.Items.Clear()

            Dim ho As Type = GetType(HowOut)

            For Each fi In ho.GetFields(BindingFlags.Static Or BindingFlags.Public)
                ddl.Items.Add(New ListItem(fi.GetValue(ho)))
            Next

        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' Create a new player in the database...
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub btnCreatePlayer_OnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnCreateNewPlayer.Click
        Try
            Using dbcontext As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)
                Dim player As New CricketBLL.Player()
                player.PlayerName = txtNewPlayerName.Text

                dbcontext.Players.InsertOnSubmit(player)
                dbcontext.SubmitChanges()

                'clear text box
                txtNewPlayerName.Text = String.Empty

                _list = Nothing
                InitPlayers()

                'temp int for selected index
                Dim index As Integer = 0

                'Done, hide modal and rebind drop downs....
                For Each item In lvBattingStats.Items
                    Dim ddl As DropDownList = CType(item.FindControl("ddlPlayers"), DropDownList)
                    If ddl Is Nothing = False Then
                        index = ddl.SelectedIndex
                        ddl.Items.Clear()
                        ddl.DataSource = _list
                        ddl.DataBind()
                        ddl.Items.Insert(0, "Select one...")
                        ddl.SelectedIndex = index
                    End If
                Next

                For Each item In lvBowlingStats.Items
                    Dim ddl As DropDownList = CType(item.FindControl("ddlPlayers"), DropDownList)
                    If ddl Is Nothing = False Then
                        index = ddl.SelectedIndex
                        ddl.Items.Clear()
                        ddl.Items.Add("Select one...")
                        ddl.DataSource = _list
                        ddl.DataBind()
                        ddl.SelectedIndex = index
                    End If
                Next

                programmaticModalPopup.Hide()

            End Using

        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' If they have checked Did not bad, disable all batting stats inputs
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub chkDNB_CheckChanged(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim chkDNB As CheckBox = CType(sender, CheckBox)

            Dim item As ListViewItem = lvBattingStats.Items(Integer.Parse(chkDNB.ValidationGroup) - 1)

            If item Is Nothing = False Then

                'Dim txtHowOut As TextBox = CType(item.FindControl("txtHowOut"), TextBox)
                Dim tBoxes As New List(Of TextBox)

                tBoxes.Add(CType(item.FindControl("txtBowler"), TextBox))
                tBoxes.Add(CType(item.FindControl("txtBallsFaced"), TextBox))
                tBoxes.Add(CType(item.FindControl("txtMins"), TextBox))
                tBoxes.Add(CType(item.FindControl("txtFours"), TextBox))
                tBoxes.Add(CType(item.FindControl("txtSixes"), TextBox))
                tBoxes.Add(CType(item.FindControl("txtBatRuns"), TextBox))

                Dim ddlHowOut As DropDownList = CType(item.FindControl("ddlHowOut"), DropDownList)

                ddlHowOut.Enabled = Not chkDNB.Checked

                ' iterate textboxes clear and set enabled state
                For Each t In tBoxes
                    t.Text = String.Empty
                    t.Enabled = Not chkDNB.Checked
                Next

            End If

        Catch ex As Exception
            ErrorLabel.Visible = True
            ErrorLabel.Text = ex.Message
        End Try
    End Sub

    ''' <summary>
    ''' If they have checked Not Out then disable the how out and bowler inputs
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub chkNO_CheckChanged(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim chkNO As CheckBox = CType(sender, CheckBox)

            Dim item As ListViewItem = lvBattingStats.Items(Integer.Parse(chkNO.ValidationGroup) - 1)

            If item Is Nothing = False Then

                Dim ddlHowOut As DropDownList = CType(item.FindControl("ddlHowOut"), DropDownList)
                Dim txtBowler As TextBox = CType(item.FindControl("txtBowler"), TextBox)

                ddlHowOut.Enabled = Not chkNO.Checked
                txtBowler.Enabled = Not chkNO.Checked

                If chkNO.Checked Then
                    txtBowler.Text = String.Empty
                End If

            End If

        Catch ex As Exception
            ErrorLabel.Visible = True
            ErrorLabel.Text = ex.Message
        End Try
    End Sub

End Class
